<template>
  <div>
    <el-dialog
      style="padding: 0px 0px 0 0px !important"
      v-model="props.show"
      :width="props.width"
      :show-close="false"
      :before-close="handleClose"
    >
      <div class="dialog_header">
        <span><i class="icon"></i>选择商品</span>
        <el-button type="" :icon="CloseBold" style="border: none" @click="handleClose"></el-button>
      </div>
      <div class="content">
        <div class="left">
          <el-tree
            style="max-width: 600px"
            :data="data.treeList"
            :props="defaultProps"
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
        <div class="right">
          <div class="right_top">
            <div class="right_top_left">
              <span>排序：</span>
              <el-button v-for="(item, i) in data.sortList" :key="i" @click="handelClickSort(item)">
                {{ item.name }}<el-icon size="14" class="el-icon--right"><Sort /></el-icon>
              </el-button>
            </div>
            <div class="right_top_center">
              <span>价格范围：</span>
              <el-input v-model="parms.minSalePrice" placeholder="输入" size="small" @change="handelChangeMinPrice" />
              <span class="to_text">至</span>
              <el-input v-model="parms.maxSalePrice" placeholder="输入" size="small" @change="handelChangeMaxPrice" />
            </div>
            <div class="right_top_right">
              <el-input
                v-model="parms.searchKey"
                placeholder="请输入商品名、商品分类、品牌名"
                size=""
                :suffix-icon="Search"
                @input="handelChangeSearchKey"
                style="width: 260px"
              />
              <el-button link type="primary" @click="handelClickMoreAttr">更多筛选</el-button>
            </div>
          </div>
          <div class="right-wrap" v-infinite-scroll="load" infinite-scroll-distance="5" :infinite-scroll-immediate="false">
            <div class="right_list">
              <el-row :gutter="20" style="width: 100%" v-if="data.shopList.length > 0">
                <el-col :span="12" v-for="(item, index) in data.shopList" :key="index">
                  <div class="childe">
                    <div class="childe_top">
                      <div class="childe_top_left mr10">
                        <img :src="item.mainPicUrl" alt="" />
                      </div>
                      <div class="childe_top_right">
                        <div class="childe_top_right_title text-over" style="max-width: 200px">{{ item.productName }}</div>
                        <div class="childe_top_right_price">
                          <span>上架类目：{{ item.preview }}</span>
                          <span class="childe_top_right_price_old">型号：{{ item.modeCode }}</span>
                          <span class="childe_top_right_price_old">ID:{{ item.productId }}</span>
                        </div>
                      </div>
                    </div>
                    <div class="childe_bottom">
                      <div>
                        特价：<span>¥{{ item.businessLowestPrice }}</span>
                      </div>
                      <div>
                        <el-button type="primary" @click="handelClickAdd(item.productId)">添加</el-button>
                      </div>
                    </div>
                  </div>
                </el-col>
              </el-row>
              <div v-else style="text-align: center; width: 100%">
                <el-empty description="这里暂时什么都没有" />
              </div>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <div>
            共 <span>{{ data.total }}</span> 个搜索结果
          </div>
          <div>
            <span @click="handelClickSelected" style="margin-right: 40px; cursor: pointer"
              >已选中：<span style="color: #007dff">{{ data.selectDate.length }}</span></span
            >
            <el-button class="jzt-button" type="info" @click="handleClose">取消</el-button>
            <el-button type="primary" @click="handelClicksubmit"> 确认导入 </el-button>
          </div>
        </div>
      </template>
    </el-dialog>
    <prodDetail :optionInfo="optionInfo" @close="handelCloseSku" @add="handelClickAddSku"></prodDetail>
    <moreAttributeFiltering
      :showDrawer="data.showDrawerMore"
      @close="handelCloseMore"
      @hadOk="handelOk"
      :categoryId="parms.categoryId"
    ></moreAttributeFiltering>
    <!-- 已选中弹框 -->
    <dialogView :title="'已选中'" :width="1200" :show="data.isSelected" @close="handelCloseSelected" @save="handelSave">
      <el-table :data="data.selectDate" class="jzt-table" stripe>
        <el-table-column label="商品信息" prop="materialName" width="420">
          <template #default="scope">
            <div class="sp_content">
              <div class="imgs">
                <img :src="scope.row.mainPicUrl" alt="" />
              </div>
              <div class="content_text">
                <p class="text-break" style="max-width: 200px">{{ scope.row.brandName }}</p>
                <p>{{ scope.row.skuSpecification }}</p>
                <p>SKU编码：{{ scope.row.skuCode }}</p>
                <p>ID:{{ scope.row.productId }}</p>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="型号" prop="modeCode"></el-table-column>
        <el-table-column label="单位" prop="productUnit">
          <template #default="scope">
            <span>
              {{ useCodeArrStore().getDictName("shop_unit", scope.row.productUnit) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="成本单价" prop="factoryRealPrice"></el-table-column>
        <el-table-column label="销售单价" prop="clinetRealPrice"></el-table-column>
        <el-table-column label="利润率" prop="profitRate"></el-table-column>
        <el-table-column label="供应商" prop="anotherName"></el-table-column>
        <el-table-column prop="warrantyTime" label="商品质保日期">
          <template #default="{ row }">
            <span>{{ row.warrantyTime || 0 }}个月</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-popconfirm title="确认删除?" @confirm="handelClickDeletPepol(scope.row)">
              <template #reference>
                <el-button link type="primary">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </dialogView>
  </div>
</template>
<script setup>
import { defineProps, defineEmits, reactive, onMounted, ref } from "vue";
import { Search, Sort, CloseBold } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import useCodeArrStore from "@/store/modules/select";
import { useRoute } from "vue-router";
// api
import {
  categoryList,
  getSpListPage,
  getSpListNewpage,
  queryProductDetial,
  saveTempProduct,
  getTempProductList,
  delTempProduct
} from "@/apis/createFile/index.js";
//组件
// import skuView from "./skuView.vue";
import dialogView from "./dialogView.vue";
import prodDetail from "./sku/prodDetail.vue";
import moreAttributeFiltering from "./moreAttributeFiltering.vue";
const emits = defineEmits(["close", "submit"]);
const route = useRoute();
const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  type: {
    type: String,
    default: "" //'1'-主材 '2'-辅材
  },
  width: {
    type: String,
    default: "500px"
  }
});
const optionInfo = ref({ isShow: false, detail: {} });
const defaultProps = {
  children: "children",
  label: "label"
};
const data = reactive({
  treeList: [],
  showDrawer: false,
  showDrawerMore: false,
  sortList: [
    // { name: "销量", sort: 1 },
    { name: "价格", sort: 2, sortSaleType: 1 }
    // { name: "新品", sort: 3 }
  ],
  shopList: [],
  productId: "",
  isSelected: false,
  selectDate: [],
  code: "",
  total: 0
});
const parms = ref({
  page: 1,
  size: 50,
  categoryId: "",
  // sortType: 0,
  sortSaleType: 1,
  searchKey: "",
  minSalePrice: 0,
  maxSalePrice: 0,
  stastsIdsStr: [],
  brandIds: [], //品牌ids
  productType: route.query.num
});

const load = () => {
  console.log("触底了，要请求分页查询接口 getSpListPages();");
  if (data.shopList.length < data.total) {
    parms.value.page++;
    getSpListPages();
  }
};

// 更多筛选
const handelClickMoreAttr = () => {
  data.showDrawerMore = true;
};
const handelCloseMore = () => {
  data.showDrawerMore = false;
};
const handelOk = (arr1, arr2, brandIds) => {
  data.showDrawerMore = false;
  const rel = arr1.flat();
  parms.value.stastsIdsStr = [...rel, ...arr2];
  parms.value.brandIds = brandIds; //品牌ids
  resetPagination(); //清空页面上的list数据，重置page=1 size=50
  getSpListPages();
};
const handleClose = () => {
  emits("close");
};
const handelSave = () => {
  data.isSelected = false;
  // data.selectDate = [];
};
const handelClickAdd = productId => {
  // 创建一个code
  if (data.code == "") {
    data.code = Date.now();
  }
  // data.showDrawer = true;
  data.productId = productId;
  optionInfo.value.isShow = true;
  let postData = new FormData();
  postData.append("productId", productId);
  queryProductDetial(postData).then(res => {
    console.log(res);
    if (res.code == 200) {
      optionInfo.value.detail = res.data;
    }
  });
};
// 关闭sku
const handelCloseSku = () => {
  optionInfo.value.isShow = false;
};
// 确认添加sku
// const businessSkuId=ref("")
const handelClickAddSku = id => {
  console.log(id, "-----");
  // businessSkuId.value = id;
  const parms = {
    code: data.code,
    businessSkuId: id
  };
  saveTempProduct(parms)
    .then(() => {
      ElMessage({
        message: "添加成功",
        type: "success"
      });
      optionInfo.value.isShow = false;
      getTempProductLists();
    })
    .catch(err => {
      console.log(err);
    });
};
// 获取已保存的数据
const getTempProductLists = () => {
  getTempProductList(data.code).then(res => {
    console.log(res);
    if (res.code == 200) {
      data.selectDate = res.data;
    }
  });
};
const handelClicksubmit = () => {
  emits("submit", data.selectDate, data.code);
};
// 点击已选中------------------------------
const handelClickSelected = () => {
  data.isSelected = true;
};
const handelCloseSelected = () => {
  data.isSelected = false;
};
const handelClose = () => {
  data.showDrawer = false;
};
const handelClickDeletPepol = item => {
  delTempProduct({ code: data.code, businessSkuId: item.businessSkuId }).then(res => {
    ElMessage({
      message: "添加成功",
      type: "success"
    });
    getTempProductLists();
  });
};
// -----------------------------------
// 获取树结构
const getTreeList = () => {
  const parms = {
    page: 1,
    size: 9999,
    productType: props.type === "1" ? 1 : 2
  };
  categoryList(parms)
    .then(res => {
      console.log(res);
      res.data.map(it => {
        it.label = it.name;
        if (it.children.length > 0) {
          it.children.map(item => {
            item.label = item.name;
            if (item.children.length > 0) {
              item.children.map(item2 => {
                item2.label = item2.name;
              });
            }
          });
        }
      });
      data.treeList = res.data;
    })
    .catch(err => {
      console.log(err);
    });
};
// 获取商品列表
const getSpListPages = () => {
  getSpListNewpage(parms.value)
    .then(res => {
      console.log(res);
      if (res.code == 200) {
        data.shopList = [...data.shopList, ...res.data.list];
        data.total = res.data.total;
      }
    })
    .catch(err => {
      console.log(err);
    });
};
const resetPagination = () => {
  data.shopList = [];
  parms.value.page = 1;
  parms.value.size = 50;
};
// 树结构点击事件
const oldNode = ref({ categoryId: null });
const handleNodeClick = item => {
  console.log(item);
  if (oldNode.value.categoryId !== item.categoryId) {
    parms.value.categoryId = item.categoryId;
    resetPagination(); //清空页面上的list数据，重置page=1 size=50
    getSpListPages();
  }
  oldNode.value = item;
};
// 点击排序
const handelClickSort = item => {
  // parms.value.sortType = item.sort;
  parms.value.sortSaleType = parms.value.sortSaleType === 1 ? 2 : 1;

  resetPagination(); //清空页面上的list数据，重置page=1 size=50
  getSpListPages();
};
// 修改最小价格
const handelChangeMinPrice = v => {
  parms.value.minSalePrice = Number(v.replace(/[^0-9.]/g, "").replace(/(\..*)\./g, "$1"));
  resetPagination(); //清空页面上的list数据，重置page=1 size=50
  getSpListPages();
};
// 修改最大价格
const handelChangeMaxPrice = v => {
  console.log(v);
  parms.value.maxSalePrice = Number(v.replace(/[^0-9.]/g, "").replace(/(\..*)\./g, "$1"));
  resetPagination(); //清空页面上的list数据，重置page=1 size=50
  getSpListPages();
};
// 关键词搜索
const handelChangeSearchKey = v => {
  parms.value.searchKey = v;
  resetPagination(); //清空页面上的list数据，重置page=1 size=50
  getSpListPages();
};
onMounted(() => {
  getTreeList();
});
</script>
<style scoped lang="scss">
:deep(.el-dialog__footer) {
  padding-top: 0 !important;
}
.icon {
  display: inline-block;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background-color: #007dff;
  margin-right: 6px;
  margin-bottom: 2px;
}
:deep(.el-tree-node__content) {
  --el-tree-node-content-height: 32px;
}
:deep(.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content) {
  --el-color-primary-light-9: #d9e8ff !important;
  color: #007dff !important;
}
.right-wrap {
  height: calc(99% - 64px);
  overflow-y: auto;
}
// 已选中的样式
.sp_content {
  display: flex;
  .imgs {
    width: 15opx;
    height: 150px;
    border-radius: 4px;
    overflow: hidden;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .content_text {
    margin-left: 18px;
    p {
      font-size: 12px;
      color: #86909c;
    }
    P:nth-child(1) {
      font-size: 14px !important;
      color: #3d3d3d !important;
    }
  }
}
.content {
  display: flex;
  border-top: 1px solid #e2e8f0;
  box-sizing: border-box;
  padding: 0 20px 0 20px;
  height: 500px;
  overflow-y: auto;
  .left {
    flex: 1;
    max-width: 200px;
    min-width: 200px;
    border-right: 1px solid #e2e8f0;
    padding-top: 20px;
    box-sizing: border-box;
    height: 99%;
    overflow-y: auto;
  }
  .right {
    flex: 2;
    padding: 0 0px 0 20px;
    &_top {
      min-height: 64px;
      max-height: 64px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .right_top_left {
        flex: 1;
        display: flex;
        align-items: center;
      }
      .right_top_center {
        display: flex;
        align-items: center;
        flex: 1;
        margin: 0 30px;
        span:nth-child(1) {
          display: inline-block;
          width: 192px;
        }
        .to_text {
          margin: 0 4px;
        }
        :deep(.el-input__wrapper) {
          width: 50px;
          height: 32px;
        }
      }
      .right_top_right {
        display: flex;
        align-items: center;
        flex: 1;
        display: flex;
        justify-content: space-between;
        :deep(.el-input__wrapper) {
          border-radius: 20px;
          width: 100%;
        }
        :deep(.el-input) {
          width: 70%;
        }
      }
    }
    &_list {
      display: flex;
      flex-wrap: wrap;
      gap: 20px;

      .childe {
        // min-width: 470px;
        flex: 1;
        min-height: 140px;
        background: #f5f7fa;
        border-radius: 2px 2px 2px 2px;
        margin: 0 0 20px 0;
        .childe_top {
          display: flex;
          padding: 20px 0 10px 20px;
          .childe_top_left {
            flex: 1;
            max-width: 80px;
            min-width: 80px;
            max-height: 80px;
            min-height: 80px;
            img {
              width: 100%;
              height: 100%;
            }
          }
          .childe_top_right {
            .childe_top_right_title {
              font-size: 16px;
              color: #3d3d3d;
              margin-bottom: 6px;
            }
            .childe_top_right_price {
              color: #86909c;
              font-size: 12px;
              display: flex;
              flex-direction: column;
              span {
                line-height: 1.5;
              }
            }
          }
        }
        .childe_bottom {
          display: flex;
          align-items: center;
          justify-content: space-between;
          height: 44px;
          border-top: 1px solid #e1e6ed;
          box-sizing: border-box;
          padding: 0px 20px;
          div:nth-child(1) {
            span {
              color: #ff3333;
            }
          }
        }
      }
    }
  }
}
.dialog-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0px -3px 10px 0px rgba(4, 24, 48, 0.1);
  height: 64px;
  padding: 0 20px;
  border-radius: 0 0 10px 10px;
  div:nth-child(1) {
    span {
      color: #ff3333;
    }
  }
}
.dialog_header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 0px 10px 10px;
}
</style>
